package com.lfz.quality_effect.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Destiny
 * @Date: 2019/10/10 09:57
 * @Description:
 */
public class ExcelListener extends AnalysisEventListener {

    private static final String SERIAL_VERSION_UID = "serialVersionUID";
    //可以通过实例获取该值
    private List<Object> datas = new ArrayList<>();
    public void invoke(Object o, AnalysisContext analysisContext) {
        if(!checkObjAllFieldsIsNull(o)) {
            datas.add(o);//数据存储到list，供批量处理，或后续自己业务逻辑处理。
            doSomething(o);//根据自己业务做处理
        }

    }
    /**
     * 判断对象中属性值是否全为空
     */
    private static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                //只校验带ExcelProperty注解的属性
                ExcelProperty property = f.getAnnotation(ExcelProperty.class);
                if(property == null || SERIAL_VERSION_UID.equals(f.getName())){
                    continue;
                }
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            //do something
        }
        return true;
    }

    private void doSomething(Object object) {
        //1、入库调用接口
    }

    public List<Object> getDatas() {
        return datas;
    }

    public void setDatas(List<Object> datas) {
        this.datas = datas;
    }

    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // datas.clear();//解析结束销毁不用的资源
    }

    public static void main(String[] args) {


    }

}
